<template>
  <div v-loading="loading">
    <div class="flex flex-start">
      <div class="tree_box">
        <el-form size="small" @submit.native.prevent>
          <el-form-item>
            <el-input size="small" placeholder="请输入部门名称" v-model.trim="searchName" maxlength="30" clearable @input="filteDepartTree"></el-input>
          </el-form-item>
        </el-form>
        <el-radio-group v-model="currentComponentIndex" size="small">
          <el-radio-button label="0">用户</el-radio-button>
          <el-radio-button label="1">权限</el-radio-button>
          <el-radio-button label="2">渠道</el-radio-button>
        </el-radio-group>
        <el-tree ref="departTreeRef" class="margin_top_20" :data="departTreeData" node-key="id" :default-expanded-keys="[currentExpandId]" :expand-on-click-node="false" :filter-node-method="filterNode">
          <div class="custom-tree-node" @click="focusNode(node, data)" slot-scope="{ node, data }">
            <span class="text-ellipsis name" :style="{'color': !data.isEnable ? 'darkgray' : ''}">{{ data.name }}</span>
            <span v-show="data.id != '0'" v-if="data.isEnable">
              <el-button type="text" size="mini" @click="updateNode(data)" v-if="roleBtns.includes('sys:department:update') || $store.getters.isAdmin"><i class="el-icon-edit"></i></el-button>
              <el-button type="text" size="mini" @click="appendNode(data, node)" v-if="roleBtns.includes('sys:department:add') || $store.getters.isAdmin"><i class="el-icon-plus"></i></el-button>
              <el-button type="text" size="mini" @click="deleteNode(data, node)" v-if="roleBtns.includes('sys:department:del') || $store.getters.isAdmin"><i class="el-icon-delete"></i></el-button>
            </span>
          </div>
        </el-tree>
        
      </div>
      <div class="content_box">
        <keep-alive>
          <component :current-node="selectNode" :tree-data="departTreeData" :is="currenComponent"></component>
        </keep-alive>
      </div>
    </div>

    <depart-form :visible.sync="isShowModel" :title="title" :depart="departTreeData" :parentNode="selectParentNode" :no-status="true" @update="appendChild"></depart-form>

    <depart-name-form :visible.sync="isShowNameModel" :title="title" :node="selectNode" @update="changeName"></depart-name-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import DepartForm from '@/views/user-management/components/departForm';
import DepartNameForm from '@/views/user-management/components/departNameForm';
import { GetDepartmentDataList, RemoveDepartmentItemData } from '@/views/user-management/services/index';
import MemberComponent from '@/views/user-management/user-depart/member';
import PowerComponent from '@/views/user-management/user-depart/power';
import ChannelComponent from '@/views/user-management/user-depart/channel';

export default {
  components: {
    MemberComponent,
    PowerComponent,
    ChannelComponent,
    DepartForm,
    DepartNameForm
  },
  data() {
    return {
      title: '',
      searchName: '',
      selectNode: null,
      waitUpdateNode: null,
      selectParentNode: [],
      currentExpandId: '',
      loading: false,
      isShowModel: false,
      isShowNameModel: false,
      departTreeData: [],

      loading: true,
      selectNode: null,

      currentId: '',
      departTreeData: [],
      currentComponentIndex: '0',
      currenComponentsList: [MemberComponent, PowerComponent, ChannelComponent]
    }
  },
  computed: {
    ...mapGetters(['roleBtns']),
    currenComponent() {
      return this.currenComponentsList[Number(this.currentComponentIndex)];
    }
  },
  methods: {
    filteDepartTree(value) {
      this.$refs.departTreeRef.filter(value);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    focusNode(node, data) {
      this.selectNode = data;
    },
    getDepartData() {
      this.loading = true;
      GetDepartmentDataList({
        proId: 4,
        depId: this.currentId ? this.currentId : '0',
        // isEnable: 1, // 0禁用1启用
        parentId: '', // 只需要一级父类时传0  只获取顶级权限一层 对应depid需要传0
        // name: this.queryName
      })
      .finally(() => this.loading = false)
      .then(res => {
        if (res.code == 200) {
          if (res.data[0].id == '0') {
            this.departTreeData = res.data[0].children;
          } else {
            this.departTreeData = res.data;
          }

          this.$nextTick(() => {
            this.selectNode = this.departTreeData[0];
            this.currentExpandId = this.selectNode.id;
            this.$refs.departTreeRef.setCurrentKey(this.currentExpandId);
          })
        }
      })
    },
    appendChild(node) {
      if (!this.waitUpdateNode.children || !this.waitUpdateNode.children.length) {
        this.waitUpdateNode.children = [node];
      } else {
        this.waitUpdateNode.children.push(node);
      }
      this.$refs.departTreeRef.append(this.waitUpdateNode, node);
    },
    changeName(event) {
      this.waitUpdateNode.name = event;
    },
    appendNode(data, node) {
      this.waitUpdateNode = data;
      this.selectParentNode = [];
      if (data.parentId && data.parentId != '0') {
        this.selectParentNode = this.deepTreeData(data.parentId, this.departTreeData);
      }
      this.selectParentNode.push(data);
      this.title = '添加子部门';
      this.isShowModel = true;
    },
    updateNode(node) {
      this.waitUpdateNode = node;
      this.title = '修改名称';
      this.isShowNameModel = true;
    },
    deleteNode(data, node) {
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            RemoveDepartmentItemData({ ids: [data.id] })
            .then(data => {
              instance.confirmButtonLoading = false;
              if (data.code == 200) {
                this.$message.success('删除成功!');
                const finderIndex = node.parent.data.children.findIndex(item => item.id == node.id);
                node.parent.data.children.splice(finderIndex, 1);
                done();
              } else {
                this.$message.success('删除失败!');
              }
            })
            .catch(error => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      });
    },
    // 深层递归返回选中的父级id
    deepTreeData(id, list) {
      let nodes = [];
      let myDeep = (parentId, childlist) => {
        if (!childlist || !childlist.length) return;
          childlist.forEach(child => {
          if (child.id == parentId) {
            nodes.unshift(child);
            myDeep(child.parentId, list);
          } else {
            if (child.children && child.children.length) {
              myDeep(parentId, child.children);
            }
          }
        })
      }

      myDeep(id, list);
      return nodes;
    }
  },
  created() {
    if (this.$route.query.departId) {
      this.currentId = this.$route.query.departId;
    } else {
      this.currentId = (this.$store.getters.userInfo) ? JSON.parse(this.$store.getters.userInfo).depId : '0';
    }
    this.loading = false;
    this.getDepartData();
  }
}
</script>

<style lang="scss" scoped>
.tree_box {
  width: 340px;
  flex: 0 0 340px;
  padding-right: 15px;
  box-sizing: border-box;
}

.content_box {
  flex: 1;
  padding: 15px;
  width: calc(100% - 340px);
  box-sizing: border-box;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 0 0 0 rgb(200 200 200 / 50%);
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: calc(100% - 24px);

  .name {
    max-width: calc(100% - 62px);
  }

  // &.isEnable {
  //   background-color: #f5f7fa;
  // }
}
::v-deep .el-tree-node__content {
  height: 38px;
}
::v-deep .el-tree-node.is-current {
  > .el-tree-node__content {
    // background-color: #f5f7fa;
    background-color: #eff6fe;
  }
}

::v-deep .el-tree-node__content {
  &:hover {
    background-color: #eff6fe;
  }
}
</style>
